//
//  CACoinCoutroller.m
//  cascade-realm
//
//  Created by QSC on 29/5/24.
//

#import "CACoinCoutroller.h"
#import "CACoinCell.h"
#import "CAGoodsModel.h"
#import <StoreKit/StoreKit.h>
//1. 账号：lanlintestpurchase1225@ll.com
         
//2. 密码：LanLinTest0825P
@interface CACoinCoutroller ()<UICollectionViewDelegate,UICollectionViewDataSource,SKPaymentTransactionObserver,SKProductsRequestDelegate>
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)UIView *topView;
@property(nonatomic,strong)NSArray * dataArray;
@property(nonatomic,copy)NSString * orderNo;
@property(nonatomic,strong)UILabel * numLabel;
@end

@implementation CACoinCoutroller

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navTitle = @"Coin Shop";
    [Http PostLogWithPage:@"purchase"];
    
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    
    [self setUpTopView];
    
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view).inset(20);
        make.top.equalTo(self.topView.mas_bottom).offset(28);
        make.bottom.equalTo(self.view).offset(-kBottomSafeHeight);
    }];
    
    [self getGoodsList];
}




- (void)setUpTopView{
    UIView * topView = [UIView new];
    self.topView = topView;
   
    [self.view addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.left.equalTo(self.view).offset(20);
        make.top.equalTo(self.navView.mas_bottom).offset(30);
        make.height.mas_equalTo(100);
    }];
    UIImageView * coinImgv = [[UIImageView alloc] initWithImage:Img(@"coins")];
    coinImgv.contentMode = UIViewContentModeScaleAspectFit;
    UIImageView * coinbg = [[UIImageView alloc] initWithImage:Img(@"coin_bg")];
    [topView addSubview:coinbg];
    [coinbg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(topView);
    }];
    [topView addSubview:coinImgv];
    [coinImgv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(topView).offset(22);
        make.centerY.equalTo(topView);
        make.size.mas_equalTo(85);
    }];
    
    UILabel *myCoinLabel = [UILabel LabelWithFont:Font(16) color:Hex(0x203B20) text:@"My Coins"];
    [topView addSubview:myCoinLabel];
    [myCoinLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topView).offset(27);
        make.left.equalTo(coinImgv.mas_right).offset(12);
    }];
    
    
    UILabel *numLabel = [UILabel LabelWithFont:BoldFont(26) color:Hex(0x4D5609) text:@""];
    numLabel.text = CAUserInfo.shared.userInfo.availableCoins;
    [topView addSubview:numLabel];
    [numLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(myCoinLabel.mas_bottom).offset(10);
        make.left.equalTo(coinImgv.mas_right).offset(12);
    }];
    self.numLabel  = numLabel;
}

- (UICollectionView *)collectionView{
    if (_collectionView == nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        CGFloat itmeW = (ScreenW - 40 - 15) / 2;
        layout.itemSize = CGSizeMake(itmeW , itmeW/162 * 140);
        
        layout.minimumInteritemSpacing = 15;

        
        UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
        collectionView.showsVerticalScrollIndicator = NO;
        collectionView.backgroundColor = [UIColor clearColor];
        collectionView.dataSource = self;
        collectionView.delegate = self;
        
        [collectionView registerClass:[CACoinCell class] forCellWithReuseIdentifier:@"CACoinCell"];
        // 去掉滚动条
        collectionView.showsHorizontalScrollIndicator = NO;
     
        collectionView.bounces = NO;
        _collectionView = collectionView;
    }
    return  _collectionView;;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return self.dataArray.count;
  
}


- (UICollectionViewCell *)collectionView:(UICollectionView *) collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    CACoinCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CACoinCell" forIndexPath:indexPath];
    
    cell.model = self.dataArray[indexPath.row];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    CAGoodsModel * model = self.dataArray[indexPath.row];
    
    [self createRecharge:model.code];


}


- (void)getGoodsList{
    NSDictionary * dic = @{
        @"isIncludeSubscription":@0,
        @"payChannel":@"IAP"
    };
    [Http postWithURL:goodsSearch params:dic success:^(id  _Nonnull responseObject) {
            
        
        self.dataArray = [CAGoodsModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        [self.collectionView reloadData];
        
    } failure:^(id  _Nonnull errObject) {
        
    }];
}


- (void)dealloc
{
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}


//购买结果反馈
- (void)paymentQueue:(nonnull SKPaymentQueue *)queue updatedTransactions:(nonnull NSArray<SKPaymentTransaction *> *)transactions {
 
    
    if (transactions.count > 0) {
        //检测是否有未完成的交易
        SKPaymentTransaction* tran = [transactions firstObject];
        if (tran.transactionState == SKPaymentTransactionStatePurchased) {
            [self completeTransaction:tran];
            [[SKPaymentQueue defaultQueue] finishTransaction:tran];//未完成的交易在此给它结束
            return;
        }
    }

    for(SKPaymentTransaction *tran in transactions){

        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased:{
//                NSLog(@"交易完成");
                // 购买后告诉交易队列，把这个成功的交易移除掉。
                //走到这就说明这单交易走完了，无论成功失败，所以要给它移出。finishTransaction
               
                [self completeTransaction:tran];
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
         
            }
                break;
                
            case SKPaymentTransactionStatePurchasing:
//                NSLog(@"商品添加进列表");
                break;
                
            case SKPaymentTransactionStateRestored:
//                NSLog(@"已经购买过商品");
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                break;
                
            case SKPaymentTransactionStateFailed:
//                NSLog(@"交易失败");
              
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                break;
                
            case SKPaymentTransactionStateDeferred:
                NSLog(@"交易还在队列里面，但最终状态还没有决定");
                break;
                
            default:
                break;
        }
        
    }
}

//接收到产品的返回信息,然后用返回的商品信息进行发起购买请求
- (void)productsRequest:(nonnull SKProductsRequest *)request didReceiveResponse:(nonnull SKProductsResponse *)response {
    NSArray *products = response.products;
  
    if(products.count == 0){//如果服务器没有产品
       return;
    }
       
   SKPayment *payment = [SKPayment paymentWithProduct:products.firstObject];
   [[SKPaymentQueue defaultQueue] addPayment:payment];//将票据加入到交易队列
}

//请求失败
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error
{
    NSLog(@"error:%@", error);
}
//反馈请求的产品信息结束后
- (void)requestDidFinish:(SKRequest *)request
{
//    NSLog(@"信息反馈结束");

}

- (void)completeTransaction:(SKPaymentTransaction*)transaction{
    
    NSString *productID =  transaction.payment.productIdentifier;

    if (self.orderNo == nil || self.orderNo.length == 0) {
        //没有orderNO就重新请求
        NSDictionary * dic = @{
            @"entry":@"",
            @"payChannel":@"IAP",
            @"source":@"",
            @"goodsCode":productID
        };
        [Http postWithURL:rechargeCreate params:dic success:^(id  _Nonnull responseObject) {
                
            if (responseObject[@"data"]!=nil) {
                self.orderNo = responseObject[@"data"][@"orderNo"];
                [self completeTransaction:transaction];
            }
            
        } failure:^(id  _Nonnull errObject) {
            
        }];
        return;
    }
    
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
    if (![[NSFileManager defaultManager] fileExistsAtPath:receiptURL.path]) {
        // 没有收据
        [EasyTextView showText:@"没有收据"];
        return;
    }

    
   
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
 
    NSString *encodeStr = [receiptData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    encodeStr = [encodeStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    encodeStr = [encodeStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];

    NSDictionary * dic = @{
        @"orderNo":self.orderNo,
        @"payload":encodeStr,
        @"transactionId":transaction.transactionIdentifier,
    };

    [Http postWithURL:rechargPeaymentIpa  params:dic success:^(id  _Nonnull responseObject) {
      
        WeakSelf
        [CAUserInfo refreshUserInfo:^{
            weakSelf.numLabel.text =  CAUserInfo.shared.userInfo.availableCoins;
        }];
        
    } failure:^(id  _Nonnull errObject) {
    
    }];
    
}

- (void)createRecharge:(NSString *)code{
    NSDictionary * dic = @{
        @"entry":@"",
        @"payChannel":@"IAP",
        @"source":@"",
        @"goodsCode":code
    };
    [Http postWithURL:rechargeCreate params:dic success:^(id  _Nonnull responseObject) {
            
        if (responseObject[@"data"]!=nil) {
            self.orderNo = responseObject[@"data"][@"orderNo"];
            [Http PostLogWithPage:@"createorder"];
            
            NSSet *set = [NSSet setWithObject:code];
            SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:set];//
            request.delegate = self;
            [request start];// 开始请求
        }
        
    } failure:^(id  _Nonnull errObject) {
        
        if (errObject[@"msg"] != nil) {
            [EasyTextView showText:[NSString stringWithFormat:@"%@",errObject[@"msg"]]];
        }
        
    }];
    
}



@end
